<template>
  <el-dialog :title="form.id ? '编辑部门' : '新增部门'" :visible="showDialog" @close="close">
    <el-form ref="form" :model="form" :rules="rules" label-width="120px">
      <el-form-item label="部门名称" prop="name">
        <el-input v-model="form.name" size="mini" style="width: 80%" placeholder="2-10个字符" />
      </el-form-item>
      <el-form-item label="部门编码" prop="code">
        <el-input v-model="form.code" size="mini" style="width: 80%" placeholder="2-10个字符" />
      </el-form-item>
      <el-form-item label="部门负责人" prop="managerId">
        <el-select v-model="form.managerId" size="mini" style="width: 80%" placeholder="请选择负责人">
          <el-option
            v-for="item in managerList"
            :key="item.id"
            :label="item.username"
            :value="item.id"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="部门介绍" prop="introduce">
        <el-input v-model="form.introduce" type="textarea" :rows="4" size="mini" style="width: 80%" placeholder="1-100个字符" />
      </el-form-item>
      <el-form-item>
        <el-button size="mini" type="primary" :loading="loading" @click="submit">确定</el-button>
        <el-button size="mini" @click="close">取消</el-button>
      </el-form-item>
    </el-form>
  </el-dialog>
</template>

<script>
import { addDepartment, getDepartmentDetail, getDepartments, getManagerList, updateDepartment } from '@/api/department'
export default {
  props: {
    showDialog: {
      type: Boolean,
      required: true
    },
    currentId: {
      type: [Number, String], // 更宽松的校验类型, 既可以是 number 又可以是 string
      required: true
    }
  },
  data() {
    return {
      loading: false, // 提交按钮的加载状态
      form: {
        code: '',
        introduce: '',
        managerId: '',
        name: ''
      },
      rules: {
        name: [
          { required: true, message: '部门名称不能为空', trigger: 'blur' },
          { min: 2, max: 10, message: '请输入2-10个字符', trigger: 'blur' },
          {
            validator: async(rule, val, cb) => {
              // console.log('现在要校验:', val)
              let res = await getDepartments()
              // 判断当前是编辑功能还是添加功能
              // 如何判断当前是编辑呢?
              if (this.form.id) {
                // 如果有 id 说明此时是编辑
                res = res.filter(item => item.id !== this.form.id)
              }
              // console.log(res)
              // res.includes() // 基本数据类型
              // console.log(res.some(item => item.name === val))
              if (res.some(item => item.name === val)) {
                // 不通过
                cb(new Error('部门名称已存在'))
              } else {
                // 通过
                cb()
              }
            },
            trigger: 'blur'
          }
        ],
        code: [
          { required: true, message: '部门编码不能为空', trigger: 'blur' },
          { min: 2, max: 10, message: '请输入2-10个字符', trigger: 'blur' },
          {
            validator: async(rule, val, cb) => {
              let res = await getDepartments()
              if (this.form.id) res = res.filter(item => item.id !== this.form.id)
              res.some(item => item.code === val) ? cb(new Error('部门编码已存在')) : cb()
            },
            trigger: 'blur'
          }
        ],
        managerId: [
          { required: true, message: '请选择部门负责人', trigger: 'change' }
        ],
        introduce: [
          { required: true, message: '部门介绍不能为空', trigger: 'blur' },
          { min: 1, max: 100, message: '请输入1-100个字符', trigger: 'blur' }
        ]
      },
      managerList: []
    }
  },
  async created() {
    this.managerList = await getManagerList()
  },
  methods: {
    // close 事件在任意会关闭 dialog 的地方都会触发, 例如: 用户点击 x 点击遮罩层
    close() {
      // console.log('有人要关我了!')
      this.$emit('update:showDialog', false)
      // 重置表单 + 清空校验规则
      this.$refs.form.resetFields()
      // 还原 form 的初始属性
      this.form = {
        code: '',
        introduce: '',
        managerId: '',
        name: ''
      }
    },
    async submit() {
      try {
        this.loading = true
        // 兜底校验
        await this.$refs.form.validate()
        // 发请求
        if (this.form.id) {
          // 发编辑请求
          await updateDepartment(this.form)
          this.$message.success('修改部门成功')
        } else {
          // 发添加请求
          await addDepartment({ ...this.form, pid: this.currentId })
          // 成功提示
          this.$message.success('新增部门成功')
        }
        // 关闭弹层并重置表单
        this.close()
        // 通知父组件更新页面
        this.$emit('updateData')
      } finally { // 不论成功还是失败最后一定会执行
        this.loading = false
      }
    },
    async getDetail() {
      // console.log('子组件:', this.currentId)
      this.form = await getDepartmentDetail(this.currentId)
    }
  }
}
</script>

<style>

</style>
